﻿using System.Reflection;

namespace PmSoft.Cache.Abstractions.EntityCache;

/// <summary>
/// 实体属性信息
/// </summary>
[Serializable]
public class EntityPropertyInfo
{
    /// <summary>
    /// 构造函数
    /// </summary>
    public EntityPropertyInfo() : this(string.Empty) { }

    internal EntityPropertyInfo(string name)
    {
        Name = name;
    }

    /// <summary>
    /// 属性名称
    /// </summary>
    public string Name { get; set; }

    public object? GetValue(object obj)
    {
        Type type = obj.GetType();
        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
        PropertyInfo? propertyInfo = type.GetProperty(Name, bindingFlags);
        if (propertyInfo == null)
            throw new ArgumentNullException(nameof(propertyInfo));
        return propertyInfo.GetValue(obj);
    }

    public void SetValue(object obj, object? value, object[]? index)
    {
        Type type = obj.GetType();
        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance;
        PropertyInfo? propertyInfo = type.GetProperty(Name, bindingFlags);
        if (propertyInfo == null)
            throw new ArgumentNullException(nameof(propertyInfo));
        propertyInfo?.SetValue(obj, value, index);
    }
}

public static class PropertyInfoExtensions
{
    public static EntityPropertyInfo AsEntityPropertyInfo(this PropertyInfo propertyInfo)
    {
        return new EntityPropertyInfo(propertyInfo.Name);
    }
}
